import { BYTEDANCE, WECHAT } from 'cc/env';
import { bannerwxwx } from './bannerwxwx';


export class BottomBannerAd {
  private static instance = null as unknown as BottomBannerAd;
  private bannerAd = null;
  private hasShow = false;
  public static Instance() {
    if (!BottomBannerAd.instance) {
      BottomBannerAd.instance = new BottomBannerAd();
    }
    return BottomBannerAd.instance;
  }
  constructor() { }
  public create() {
    const that = this;
    // 创建之前，先销毁旧广告
    this.destroy();
    this.hasShow = false;
    if (WECHAT) {
      const { screenWidth, screenHeight } = wx.getSystemInfoSync();
      this.bannerAd = wx.createBannerAd({
        adUnitId: bannerwxwx.wxbannerid,
        style: { left: screenWidth / 2 - 160, top: 0.75 * screenHeight, width: 320 }
      });
      console.log('bottom ad ', screenWidth, screenHeight);
      this.bannerAd.onLoad(() => {
        if (that.hasShow) {
          that.show();
        }
      });
      this.bannerAd.onError((err: any) => {
        console.log('banner ad error ', err);
      })
    } else if (BYTEDANCE) {
      const { screenWidth, screenHeight } = tt.getSystemInfoSync();
      this.bannerAd = tt.createBannerAd({
        adUnitId: '9f5lqd2rjd128a232p',
        style: { left: screenWidth / 2 - 104, top: screenHeight, width: 208 }
      });
      console.log('bottom ad ', screenWidth, screenHeight);
      this.bannerAd.onLoad(() => {
        if (that.hasShow) {
          that.show();
        }
      });
      this.bannerAd.onError((err: any) => {
        console.log('banner ad error ', err);
      })
    }
  }

  public show() {
    if (!this.bannerAd) {
      return;
    }
    this.hasShow = true;
    if (WECHAT) {
      this.bannerAd.show().catch((err: any) => {
        console.log('bottom banner ad show error ', err);
      })
    }
  }
  // 用户自己手动关闭
  public hide() {
    this.hasShow = false;
    if (!this.bannerAd) {
      return;
    }
    if (WECHAT) {
      this.bannerAd.hide();
    }
  }
  public destroy() {
    if (!this.bannerAd) {
      return;
    }
    if (WECHAT) {
      this.bannerAd.destroy();
    }
  }
}